package com.skillworld.webapp.web.pages.rest.game;


import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.gamemap.Position;
import com.skillworld.webapp.model.gameservice.GameService;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;


@ContentType("text/xml")
public class SavePosition
{    
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;

    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private GameService gameService;

    @Inject
    private Request request;
   

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String mapName = request.getParameter("map");
        String posxParam = request.getParameter("pos-x");
        String posyParam = request.getParameter("pos-y");
        
        if (posxParam == null || posyParam == null)
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }

        try 
        {
            double posx = Double.parseDouble(posxParam);
            double posy = Double.parseDouble(posyParam);
            this.gameService.savePosition(userSession.getUserId(), 
                                            mapName, 
                                            new Position(posx,posy));
        }
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.APPLICATION_ERROR; }
    }
}
